<?php
namespace collecter\controllers;

use app\models\Knowledge;
use collecter\components\PageTask;
use common\libraries\Collector;
use common\libraries\File;
use common\models\Note;
use common\models\User;
use collecter\models\Site;
use Yii;
use common\components\PageView;
use common\models\Category;
use yii\helpers\Url;

/**
 * NoteController
 */
class PageTaskController extends \yii\web\Controller {

    public $loginUid = 0;
    public $loginUser = null;
    public $enableCsrfValidation = false;

    public function init(){
        parent::init();
        header("Content-Type;text/html; charset=utf-8");

    }

    public function actionIndex(){

        //$r = Yii::$app->sqlite->createCommand("SELECT * FROM StdItems")->queryAll();

        //echo '<pre>';print_r($r);exit;

        $tasks = Yii::$app->sqlite->createCommand("SELECT t.* FROM `page_task` AS t")->queryAll();

        $data = [
            'tasks' => $tasks,
        ];

        return $this->renderPartial('index', $data);
    }

    public function actionList(){

        $c1 = isset($_GET["c1"]) ? intval($_GET["c1"]) : 0;
        $c2 = isset($_GET["c2"]) ? intval($_GET["c2"]) : 0;
        $c3 = isset($_GET["c3"]) ? intval($_GET["c3"]) : 0;
        $cid = isset($_GET["cid"]) ? intval($_GET["cid"]) : 0;
        $mobile = (isset($_GET["mobile"]) && strtolower($_GET["mobile"]) != 'false') ? true : false;

        $categorys = \common\models\Category::getData();
        //print_r($categorys);

        $treeData = \common\models\Category::getTree($categorys);
        //print_r($treeData);

        $where = " WHERE TRUE";
        $con1 = ($c1 == 0) ? "" : " AND k.c1=".$c1;
        $con1 = ($c2 == 0) ? $con1 : " AND k.c2=".$c2;
        $con1 = ($c3 == 0) ? $con1 : " AND k.c3=".$c3;
        $where = $where.$con1;

        $db = Yii::$app->db;
        $dataCount = $db->createCommand('SELECT count(*) as dataCount FROM {{%note}} AS k'.$where)->queryScalar();

        $perPage = 20;
        $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;

        $pv = new PageView($dataCount, $perPage, $currentPage);

        $sql = 'SELECT k.id, k.cid, k.question, k.answer, k.`right`, t.name AS tname, c2.name AS cname2, k.last_right_time FROM {{%note}} AS k '.
            'LEFT JOIN {{%note_category}} AS t ON k.c1=t.id '.
            'LEFT JOIN {{%note_category}} AS c2 ON k.c2=c2.id'.
            $where." ORDER BY k.id ASC".$pv->limitSql;

        $knowledge =  $db->createCommand($sql)->queryAll();

        $data = [
            "c1" => $c1,
            "c2" => $c2,
            "c3" => $c3,
            "cid" => $cid,
            "categorys" => $categorys,
            'treeData' => $treeData,
            "knowledge"=> $knowledge,
            "pv"=>$pv,
            "mobile"=>$mobile,
            'loginUid' => $this->loginUid,
        ];

        if($mobile){
            return $this->renderPartial('mobile', $data);
        }else{
            return $this->renderPartial('list', $data);
        }
    }

    public function actionEdit(){

        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;


        if($id > 0){
            $task = Yii::$app->sqlite->createCommand("SELECT t.* FROM `page_task` AS t WHERE t.id=".$id)->queryOne();
            //print_r($task);
        }else{
            $task = [];
        }

        $data = [
            'id' => $id,
            'task' => $task,
        ];
        return $this->renderPartial('edit', $data);
    }

    public function actionAsyncEdit(){
        $id = isset($_POST["id"]) ? intval($_POST["id"]) : "";

        $name = isset($_POST["name"]) ? addslashes($_POST["name"]) : "";
        if(empty($name)){
            exit(json_encode(["code"=>400, "缺少参数name"], JSON_UNESCAPED_UNICODE));
        }

        $impl_class = isset($_POST["impl_class"]) ? addslashes($_POST["impl_class"]) : "";
        if(empty($impl_class)){
            exit(json_encode(["code"=>400, "缺少标识"], JSON_UNESCAPED_UNICODE));
        }

        //页面数据
        $pagedata = isset($_POST["pagedata"]) ? addslashes($_POST["pagedata"]) : "";
        if(empty($pagedata)){
            exit(json_encode(["code"=>400, "页面数据不能为空"], JSON_UNESCAPED_UNICODE));
        }

        //总页数
        $page_sum = isset($_POST["page_sum"]) ? addslashes($_POST["page_sum"]) : "";
        if(empty($page_sum)){
            exit(json_encode(["code"=>400, "总页数不能为空"], JSON_UNESCAPED_UNICODE));
        }

        $data = [
            'name' => $name,
            'impl_class' => $impl_class,
            'pagedata' => $pagedata,
            'page_sum' => $page_sum,
        ];

        try{
            if($id > 0){
                Yii::$app->sqlite->createCommand()->update('page_task', $data, "id=:id", [':id'=>$id])->execute();
            }else{
                Yii::$app->sqlite->createCommand()->insert('page_task', $data)->execute();
            }
            exit(json_encode(["code"=>200, "成功"], JSON_UNESCAPED_UNICODE));
        }catch(\Exception $e){
            $excepInfo = ["code"=>500, "info"=>"页面数据不能为空", "exception"=>[
                "file" => $e->getFile(),
                "line" => $e->getLine(),
                "message" => $e->getMessage(),
            ]];
            exit(json_encode($excepInfo, JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 详情页
     * @return string
     */
    public function actionDetail(){

        //任务ID
        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
        if(empty($id)){
            exit(json_encode(["code"=>400, "参数错误：缺少任务ID"], JSON_UNESCAPED_UNICODE));
        }

        //任务详情
        $detail = Yii::$app->sqlite->createCommand("SELECT t.* FROM `page_task` AS t WHERE t.id=".$id)->queryOne();
        if(empty($detail)){
            exit(json_encode(["code"=>400, "查不到任务详情"], JSON_UNESCAPED_UNICODE));
        }
        //       print_r($task);exit;

        //自动运行
        $run = isset($_GET["run"]) ? intval($_GET["run"]) : 0;

        //页数
        $page = isset($_GET["page"]) ? intval($_GET["page"]) : 1;

        //列表数据
        $impl_class = isset($detail["impl_class"]) ? $detail["impl_class"] : "";
        if(empty($impl_class)){
            exit(json_encode(["code"=>400, "缺少实现类"], JSON_UNESCAPED_UNICODE));
        }

        $ImplClass = "\\collecter\\data\\tasks\\".$impl_class;
        $obj = new $ImplClass();


        $tasks = $obj->getTasks($page);

        //print_r($tasks);exit;


        $data = [
            "id" => $id,
            "page" => $page,
            "run" => $run,
            "detail" => $detail,
            "tasks" => $tasks,
        ];
        return $this->renderPartial('detail', $data);
    }

    public function actionAsyncRemove(){
        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
        if(empty($id)){
            exit(json_encode(["code"=>400, "info"=>"请输入ID"], JSON_UNESCAPED_UNICODE));
        }

        $transation = Yii::$app->sqlite->beginTransaction();
        try{
            Yii::$app->sqlite->createCommand("DELETE FROM page_task WHERE id=".$id)->execute();
            $transation->commit();
            exit(json_encode(["code"=>200, "info"=>"删除成功"], JSON_UNESCAPED_UNICODE));
        }catch (\Exception $e){
            $transation->rollBack();
            $excInfo = [
                'file'=>$e->getFile(),
                'line'=>$e->getLine(),
                'message'=>$e->getMessage(),
            ];
            exit(json_encode(["code"=>500, "info"=>"异常", "exception"=>$excInfo], JSON_UNESCAPED_UNICODE));
        }
    }

    public function actionOnTask(){

        $url = isset($_POST["url"]) ? addslashes($_POST["url"]) : "";
//        $url = isset($_POST["url"]) ? addslashes($_POST["url"]) : "";


        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
        if(empty($id)){
            exit(json_encode(["code"=>400, "参数错误：缺少任务ID"], JSON_UNESCAPED_UNICODE));
        }

        //任务详情
        $detail = Yii::$app->sqlite->createCommand("SELECT t.* FROM `page_task` AS t WHERE t.id=".$id)->queryOne();
        if(empty($detail)){
            exit(json_encode(["code"=>400, "查不到任务详情"], JSON_UNESCAPED_UNICODE));
        }

        //列表数据
        $impl_class = isset($detail["impl_class"]) ? $detail["impl_class"] : "";
        if(empty($impl_class)){
            exit(json_encode(["code"=>400, "缺少实现类"], JSON_UNESCAPED_UNICODE));
        }

        $link = isset($_POST["link"]) ? addslashes($_GET["link"]) : "";

        /**
         * @var PageTask $obj
         */
        $ImplClass = "\\collecter\\data\\tasks\\".$impl_class;
        $obj = new $ImplClass();

        $task = $obj->getTask($link);


        exit(json_encode(["code"=>200, "info"=>"成功", "url"=>$url, "data"=>["id"=>$id]], JSON_UNESCAPED_UNICODE));
    }

}
